<?php
/****************************************
 *             gamedata.php             *
 *                                      *
 *  Returns the game name and icon for  *
 *              a game id.              *
 *                                      *
 *       Licensed under the GPLv2       *
 *      Written by: Michiel Lowijs      *
 ****************************************/

// If the xfire_games.ini file is older than a day, refresh it
if (!file_exists('xfire_games.ini') || filemtime('xfire_games.ini') + 86400 < time())
	file_put_contents('xfire_games.ini', file_get_contents('http://media.xfire.com/xfire/xfire_games.ini'));

if (isset($_GET['ver']))
	die(get_ini_version());	

if (isset($_GET['game']))
	echo get_gamedata($_GET['game']);

/*
 * Get matches for game id.
 */
function find_game($gameid) {
	$ini = file_get_contents('xfire_games.ini');
	$regex = '/\[' . $gameid . '.*\]\nLongName=(.*)\nShortName=(.*)\n/U';

	$matches = array();
	if (preg_match_all($regex, $ini, $matches, PREG_SET_ORDER) === 0)
		return find_game('-1');
	else
		return $matches[0];
}
 
/*
 * Get game data.
 */
function get_gamedata($gameid) {
	$data = find_game($gameid);
	
	$imageurl = 'http://media.xfire.com/xfire/xf/images/icons';
	$filename = $data[2] . '.gif';

	if (!file_exists($filename))
		file_put_contents($filename, file_get_contents("$imageurl/$filename"));

	$imglen = filesize($filename);
	$low = 0xFF & $imglen;
	$high = (0xFF00 & $imglen) >> 8;
	
	$buffer = chr(strlen($data[1])) . chr($low) . chr($high) . $data[1] . file_get_contents($filename);
	
	return $buffer;
}

/*
 * Get version of xfire_games.ini
 */
function get_ini_version() {
	$regex = '/Version=(.*)/';
	$matches = array();
	preg_match_all($regex, file_get_contents('xfire_games.ini'), $matches, PREG_SET_ORDER);
	return $matches[0][1];
}
?>